// 初始化设置
function initSettings() {
  // 加载字体大小设置
  const savedFontSize = localStorage.getItem("fontSize");
  if (savedFontSize) {
    document.documentElement.style.setProperty(
      "--content-font-size",
      savedFontSize + "px"
    );
  }

  // 加载暗黑模式设置
  const darkMode = localStorage.getItem("darkMode");
  const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;

  if (darkMode === "true" || (darkMode === null && prefersDark)) {
    document.documentElement.classList.add("dark-mode");
    document.documentElement.classList.remove("light-mode");
  } else if (darkMode === "false") {
    document.documentElement.classList.add("light-mode");
    document.documentElement.classList.remove("dark-mode");
  }
}

// 保存当前章节
function saveCurrentChapter() {
  const currentUrl = window.location.href;
  localStorage.setItem("lastReadChapter", currentUrl);
}

// 字体大小调整 - 调整正文和容器字体大小
document.getElementById("decrease-font").addEventListener("click", function () {
  const currentSize = parseFloat(
    getComputedStyle(document.documentElement).getPropertyValue(
      "--content-font-size"
    )
  );
  const newSize = Math.max(12, currentSize - 1);
  document.documentElement.style.setProperty(
    "--content-font-size",
    newSize + "px"
  );
  document.documentElement.style.setProperty(
    "--body-font-size",
    newSize + "px"
  );
  localStorage.setItem("fontSize", newSize);
});

document.getElementById("increase-font").addEventListener("click", function () {
  const currentSize = parseFloat(
    getComputedStyle(document.documentElement).getPropertyValue(
      "--content-font-size"
    )
  );
  const newSize = Math.min(24, currentSize + 1);
  document.documentElement.style.setProperty(
    "--content-font-size",
    newSize + "px"
  );
  document.documentElement.style.setProperty(
    "--body-font-size",
    newSize + "px"
  );
  localStorage.setItem("fontSize", newSize);
});

// 键盘导航功能 - 使用CSS类简化选择器
function setupKeyboardNavigation() {
  document.addEventListener("keydown", function (event) {
    // 忽略在输入框等可编辑元素中按下的按键
    if (
      event.target.tagName === "INPUT" ||
      event.target.tagName === "TEXTAREA" ||
      event.target.isContentEditable
    ) {
      return;
    }

    // 左箭头键 - 上一章
    if (event.key === "ArrowLeft") {
      const prevChapterLink = document.querySelector(".prev-chapter");
      if (prevChapterLink) {
        prevChapterLink.click();
      }
    }
    // 右箭头键 - 下一章
    else if (event.key === "ArrowRight") {
      const nextChapterLink = document.querySelector(".next-chapter");
      if (nextChapterLink) {
        nextChapterLink.click();
      }
    }
  });
}

// 监听页面离开，保存当前章节
window.addEventListener("beforeunload", saveCurrentChapter);

// 初始化设置
initSettings();
// 设置键盘导航
setupKeyboardNavigation();
